/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2024-09-02
 * Time: 20:44
 */

/**
 * 有三个线程，分别只能打印A，B和C
 * 要求按顺序打印ABC，打印10次
 * 输出示例：
 * ABC
 * ABC
 * ABC
 * ABC
 * ABC
 * ABC
 * .....
 */
public class demo3 {
    public static void main(String[] args) throws InterruptedException {

        Object locker1 = new Object();
        Object locker2 = new Object();
        Object locker3 = new Object();

        Thread A = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                synchronized (locker3) {
                    try {
                        locker3.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print("A");
                synchronized (locker1) {
                    locker1.notify();
                }
            }
        });
        Thread B = new Thread(() -> {

            for (int i = 0; i < 10; i++) {
                synchronized (locker1) {
                    try {
                        locker1.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print("B");
                synchronized (locker2) {
                    locker2.notify();
                }
            }
        });
        Thread C = new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                synchronized (locker2) {
                    try {
                        locker2.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("C");
                synchronized (locker3) {
                    locker3.notify();
                }
            }
        });

        A.start();
        B.start();
        C.start();
        Thread.sleep(1000);//可能存在的问题:先执行到notify,后执行到wait,这个时候并没有起到作用,解决办法:notify之前sleep
        synchronized (locker3){
            locker3.notify();
        }
    }
}
